package com.common.data.desensitization.common.handler;

import com.common.data.desensitization.common.annotation.DesensitizationRule;
import com.common.data.desensitization.common.utils.DesensitizationServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DesensitizeByRegexHandler implements DesensitizationHandler{
    private static final Logger logger = LoggerFactory.getLogger(DesensitizeByRegexHandler.class);

    @Override
    public String desensitize(String originalValue, DesensitizationRule rule) {
        if (!StringUtils.hasText(rule.regex())) {
            logger.warn("Regex is empty for REGEX_REPLACE strategy.");
            return originalValue;
        }
        try {
            Pattern pattern = Pattern.compile(rule.regex());
            Matcher matcher = pattern.matcher(originalValue);
            if (matcher.find()) { // find() or replaceAll directly
                return matcher.replaceAll(rule.replacement());
            }
        } catch (Exception e) {
            logger.error("Error during regex desensitization: {}", e.getMessage());
        }
        return originalValue;
    }
}
